// 文档模块 Store
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { 
  DocLesson, 
  DocCategory, 
  DocTag, 
  DocSearchParams, 
  DocStats,
  DocImportTask,
  DocImportConfig,
  DocSource
} from '@/types/docs'
import { http } from '@/utils/http'
import { useAppStore } from './app'

export const useDocsStore = defineStore('docs', () => {
  // 状态
  const categories = ref<DocCategory[]>([])
  const lessons = ref<DocLesson[]>([])
  const tags = ref<DocTag[]>([])
  const currentLesson = ref<DocLesson | null>(null)
  const currentCategory = ref<DocCategory | null>(null)
  const loading = ref(false)
  const searchKeyword = ref('')
  const stats = ref<DocStats | null>(null)
  const importTask = ref<DocImportTask | null>(null)

  // 文档源配置
  const docSources = ref<Record<string, DocSource>>({
    cursor: {
      name: 'Cursor 官方文档',
      url: 'https://cursor-docs.apifox.cn/',
      version: '1.0',
      language: 'zh-CN'
    }
  })

  // 计算属性
  const categoryTree = computed(() => {
    const rootCategories = categories.value.filter(cat => !cat.parentId && cat.isDocCategory)
    return rootCategories.map(parent => ({
      ...parent,
      children: categories.value.filter(cat => cat.parentId === parent.id)
    }))
  })

  const filteredLessons = computed(() => {
    if (!searchKeyword.value) return lessons.value
    
    const keyword = searchKeyword.value.toLowerCase()
    return lessons.value.filter(lesson => 
      lesson.title.toLowerCase().includes(keyword) ||
      lesson.content.toLowerCase().includes(keyword) ||
      lesson.excerpt?.toLowerCase().includes(keyword)
    )
  })

  const lessonsByCategory = computed(() => {
    const map = new Map<number, DocLesson[]>()
    lessons.value.forEach(lesson => {
      const categoryLessons = map.get(lesson.categoryId) || []
      categoryLessons.push(lesson)
      map.set(lesson.categoryId, categoryLessons)
    })
    return map
  })

  // 文档分类方法
  const fetchDocCategories = async () => {
    try {
      loading.value = true
      const response = await http.get('/api/docs/categories')
      categories.value = response.data.data || []
    } catch (error) {
      const appStore = useAppStore()
      appStore.showError('获取文档分类失败')
    } finally {
      loading.value = false
    }
  }

  const createDocCategory = async (data: Partial<DocCategory>) => {
    try {
      const response = await http.post('/api/docs/categories', {
        ...data,
        isDocCategory: true
      })
      await fetchDocCategories()
      return response.data.data
    } catch (error) {
      throw error
    }
  }

  const updateDocCategory = async (id: number, data: Partial<DocCategory>) => {
    try {
      const response = await http.put(`/api/docs/categories/${id}`, data)
      await fetchDocCategories()
      return response.data.data
    } catch (error) {
      throw error
    }
  }

  const deleteDocCategory = async (id: number) => {
    try {
      await http.delete(`/api/docs/categories/${id}`)
      await fetchDocCategories()
    } catch (error) {
      throw error
    }
  }

  // 文档内容方法
  const fetchDocLessons = async (params?: DocSearchParams) => {
    try {
      loading.value = true
      const response = await http.get('/api/docs/lessons', { params })
      lessons.value = response.data.data || []
      return response.data
    } catch (error) {
      const appStore = useAppStore()
      appStore.showError('获取文档列表失败')
    } finally {
      loading.value = false
    }
  }

  const fetchDocLesson = async (id: number | string) => {
    try {
      loading.value = true
      const response = await http.get(`/api/docs/lessons/${id}`)
      currentLesson.value = response.data.data
      return response.data.data
    } catch (error) {
      const appStore = useAppStore()
      appStore.showError('获取文档详情失败')
    } finally {
      loading.value = false
    }
  }

  const createDocLesson = async (data: Partial<DocLesson>) => {
    try {
      const response = await http.post('/api/docs/lessons', data)
      await fetchDocLessons()
      return response.data.data
    } catch (error) {
      throw error
    }
  }

  const updateDocLesson = async (id: number, data: Partial<DocLesson>) => {
    try {
      const response = await http.put(`/api/docs/lessons/${id}`, data)
      await fetchDocLessons()
      return response.data.data
    } catch (error) {
      throw error
    }
  }

  const deleteDocLesson = async (id: number) => {
    try {
      await http.delete(`/api/docs/lessons/${id}`)
      await fetchDocLessons()
    } catch (error) {
      throw error
    }
  }

  // 文档标签方法
  const fetchDocTags = async () => {
    try {
      const response = await http.get('/api/docs/tags')
      tags.value = response.data.data || []
    } catch (error) {
      console.error('获取文档标签失败:', error)
    }
  }

  // 文档导入方法
  const importDocs = async (config: DocImportConfig) => {
    try {
      loading.value = true
      const response = await http.post('/api/docs/import', config)
      importTask.value = response.data.data
      return response.data.data
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  const getImportStatus = async (taskId: number) => {
    try {
      const response = await http.get(`/api/docs/import/${taskId}/status`)
      importTask.value = response.data.data
      return response.data.data
    } catch (error) {
      console.error('获取导入状态失败:', error)
    }
  }

  // 文档同步方法
  const syncDocSource = async (source: string) => {
    try {
      loading.value = true
      const response = await http.post(`/api/docs/sync/${source}`)
      const appStore = useAppStore()
      appStore.showSuccess('文档同步任务已启动')
      return response.data.data
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 文档统计方法
  const fetchDocStats = async () => {
    try {
      const response = await http.get('/api/docs/stats')
      stats.value = response.data.data
      return response.data.data
    } catch (error) {
      console.error('获取文档统计失败:', error)
    }
  }

  // 搜索方法
  const searchDocs = async (params: DocSearchParams) => {
    try {
      loading.value = true
      const response = await http.get('/api/docs/search', { params })
      return response.data.data
    } catch (error) {
      const appStore = useAppStore()
      appStore.showError('搜索文档失败')
    } finally {
      loading.value = false
    }
  }

  // 工具方法
  const getCategoryPath = (categoryId: number): DocCategory[] => {
    const path: DocCategory[] = []
    let current = categories.value.find(cat => cat.id === categoryId)
    
    while (current) {
      path.unshift(current)
      const parentId = current.parentId
      current = parentId 
        ? categories.value.find(cat => cat.id === parentId)
        : undefined
    }
    
    return path
  }

  const getDocSource = (sourceKey: string): DocSource | undefined => {
    return docSources.value[sourceKey]
  }

  // 重置状态
  const resetState = () => {
    categories.value = []
    lessons.value = []
    tags.value = []
    currentLesson.value = null
    currentCategory.value = null
    searchKeyword.value = ''
    stats.value = null
    importTask.value = null
  }

  return {
    // 状态
    categories,
    lessons,
    tags,
    currentLesson,
    currentCategory,
    loading,
    searchKeyword,
    stats,
    importTask,
    docSources,
    
    // 计算属性
    categoryTree,
    filteredLessons,
    lessonsByCategory,
    
    // 方法
    fetchDocCategories,
    createDocCategory,
    updateDocCategory,
    deleteDocCategory,
    fetchDocLessons,
    fetchDocLesson,
    createDocLesson,
    updateDocLesson,
    deleteDocLesson,
    fetchDocTags,
    importDocs,
    getImportStatus,
    syncDocSource,
    fetchDocStats,
    searchDocs,
    getCategoryPath,
    getDocSource,
    resetState
  }
}) 